define([
    'require',
    'angular',
    'underscore'
], function (require, angular, _) {
    return function ($rootScope, $scope, $routeParams, $http, $compile, RuleSerivce, GillionMsg, Arrays) {
        var tableId = $routeParams.tableId;
        RuleSerivce.promises().then(function () {
            $scope.status=$rootScope.currPackage.status;
        });
        function _rowIdGenerate() {
            return $scope._rowId++;
        }

        var initCells = {},
            initRowIds = [],
            modify = false;
        function initDecisions() {
            $scope._rowId = 0;
            $scope.editCells = {};
            $http({
                method: 'GET',
                url: '/grule-manager/decision-tables/loadDecision',
                params: {
                    tableId: tableId
                }
            }).success(function(resp){
                var data;
                if (resp.success) {
                    modify = false;
                    data = resp.data;
                    $scope.cols = data.cols;
                    $scope.rows = data.rows;
                    angular.forEach($scope.rows, function(row){
                        row._id = _rowIdGenerate();
                    });
                    initRowIds = Arrays.extractToArray($scope.rows, 'id');
                    initCells = {};
                    angular.forEach(data.cells, function(cell) {
                        initCells[cell.rowId + '_' + cell.colId] = cell;
                    });
                }
            });
        }
        initDecisions();

        $scope.saveStatus=function (){
            $scope.save(false);
        }

        $scope.showColConfig = function(init) {
            if (typeof init != 'boolean') init = true;
            GillionMsg.showUrl({
                title: '配置条件列',
                url: 'rule/decision/colConfig',
                data: {
                    decisionTable: $rootScope.currDecisionTable,
                    modelId: $rootScope.currPackage.businessModelId,
                    init: init
                },
                width: 500,
                height: 400,
                onClose: function(data){
                    if (data === true) {
                        initDecisions();
                    }
                }
            });
        };

        $scope.showColConfig2 = function() {
            if (modify) {
                GillionMsg.confirm('警告', '当前配置页面已修改，配置条件列前请先保存当前决策表配置', function(flag){
                    if (flag) {
                        $scope.save(function(){
                            $scope.showColConfig(false);
                        });
                    }
                });
            } else {
                $scope.showColConfig(false);
            }
        };

        $scope.editRow = function(index) {
            var row = $scope.rows[index];
            GillionMsg.showUrl({
                title: '编辑行',
                url: 'rule/decision/editRow',
                data: row,
                width: 500,
                height: 300,
                onClose: function(resp) {
                    if (resp.success) {
                        $scope.rows[index] = resp.row;
                        $scope.rows = _.sortBy($scope.rows, function(row){
                            if (row.priority) {
                                return - row.priority;
                            }
                            return 0;
                        });
                        console.log($scope.rows)
                        $scope.save(false);
                    }
                }
            });
        };

        $scope.removeRow = function(index){
            modify = true;
            $scope.rows.splice(index, 1);
            $scope.save(false);
        };

        $scope.addRow = function() {
            var maxPriorityRow = _.max($scope.rows, function(row){ return row.priority; }),
                maxPriority = maxPriorityRow.priority + 1 || 1;
            modify = true;
            $scope.rows.unshift({
                _id: _rowIdGenerate(),  //行虚id
                priority: maxPriority
            });
            $scope.save(false);
        };

        $scope.editCell = function(row, col) {
            var key = row._id + '_' + col.colId,
                cell = $scope.editCells[key];
            if (!cell) {
                if (row.id) {
                    cell =  initCells[row.id + '_' + col.colId];
                }
            }
            if (!cell) {
                cell = {
                    _rowId: row._id, //行虚id
                    rowId: row.id,   //行真实id
                    colId: col.colId
                }
            }

            GillionMsg.showUrl({
                title: '编辑条件',
                url: 'rule/decision/cellCondition',
                data: {
                    tableId: tableId,
                    modelId:$scope.currPackage.businessModelId,
                    col: col,
                    cell: cell
                },
                width: 880,
                height: 500,
                onClose: function(data) {
                    if (typeof data == 'string') {
                        modify = true;
                        cell.conditions = data;
                        $scope.editCells[key] = cell;
                    }
                    $scope.save(false);
                }
            });
        };

        $scope.editDedution = function(row) {
            GillionMsg.showUrl({
                title: '推论设置',
                url: 'rule/decision/dedution',
                data: {
                    row: row,
                    modelId:$scope.currPackage.businessModelId
                },
                width: 880,
                height: 500,
                onClose: function(data){
                    if (angular.isArray(data)) {
                        modify = true;
                        row.dedution = JSON.stringify(data);
                    }
                    $scope.save(false);
                }
            });
        };

        $scope.formatterCell = function(row, col) {
            var key = row._id + '_' + col.colId,
                cell = $scope.editCells[key],
                result;
            if (!cell) {
                if (row.id) {
                    cell =  initCells[row.id + '_' + col.colId] || {};
                } else {
                    cell = {};
                }
            }
            if(cell.conditions && cell.conditions!='{}') {
                var json = eval("(" + cell.conditions + ")");
                result = showValue(json);
            }
            return result;
        };

        $scope.formatterDedution = function(row) {
            var result="";
            if(row.dedution) {
                var json = eval("(" + row.dedution + ")");
                result = setDedution(json);
            }
            return result;
        };

        function setDedution(list){
            var result="";
            for(var i=0;i<list.length;i++){
                if(list[i].type=="setRtnValue"){
                    result+="返回:";
                    result+= showValue(list[i].value);
                }else if(list[i].type=="setVariable"){
                    result+="变量赋值:  KEY为:"+list[i].key+",   值为:";
                    result+=showValue(list[i].value);
                }else if(list[i].type=="setModel"){
                    result+="属性赋值:  属性名:"+list[i].modelId+",   值为:";
                    result+=showValue(list[i].modelValue);
                }else if(list[i].type=="breakPackage"){
                    result+="跳出规则包；";
                }else if(list[i].type=="breakAssembly"){
                    result+="跳出决策表；";
                }else if(list[i].type=="execute"){
                    if(list[i].code=="list"){
                        result+="循环"+list[i].source.variableName+"；";
                    }else if(list[i].code=="listEnd"){
                        result+="循环结束；"
                    }else if(list[i].code=="judge"){
                        result+="判断：";
                        result+=showValue(list[i].source);
                    }else if(list[i].code=="judgeEnd"){
                        result+="判断结束；"
                    }
                }
            }
            return result;
        }

        function showValue(json){
            var result="";
            if(json.type=="parenthesis"){
                result +="(";
                result += showValue(json.expression);
                result +=")";
            }else {
                if (json.left != null && json.right != null) {
                    result += showValue(json.left);
                    result += json.oper;
                    result += showValue(json.right);
                } else {
                    if(json.type=="model") {
                        result += json.value;
                    }else if(json.type=="variable"){
                        result += json.variableName;
                    }else if(json.type =="addHours"){
                        result +=showValue(json.source)+"  加"+json.hours +"小时";
                    }else if(json.type=="const"){
                        result +=json.value;
                    }else if(json.type =="lastDateTime"){
                        result +=showValue(json.source)+"  当天最后时间"
                    }else if(json.type =="startWith"){
                        result +=showValue(json.source) +" 以"+json.str+"开始";
                    }else if(json.type =="endsWith"){
                        result +=showValue(json.source) +" 以"+json.str+"结束";
                    }else if(json.type =="matchWith"){
                        result +=showValue(json.source) +" 包含"+json.str;
                        }else if(json.type =="JDBCService"){
                        result +="调用JDBC组件："+showValue(json.sqlName);
                    }else if(json.type =="listValue"){
                        result +="获取"+json.source;
                    }
                }
            }
            return result;
        }


        $scope.save = function(fn) {
            var rows = $scope.rows,
                rowIds = Arrays.extractToArray(rows, 'id'),
                delRowIds = [],
                addRows = [],
                updateRows = [],
                editCells = $scope.editCells,
                key, editCell, _rowId,
                updateCells = [],
                existsRowAddCells = [];

            angular.forEach(initRowIds, function(initRowId){
                if (Arrays.indexOf(rowIds, initRowId) == -1) {
                    delRowIds.push(initRowId);
                }
            });
            angular.forEach(rows, function(row){
                if (row.id) {
                    updateRows.push(row)
                } else {
                    addRows.push(row);
                }
            });

            var cache = {};
            angular.forEach(addRows, function(addRow){
                cache[addRow._id] = addRow;
            });

            for (key in editCells) {
                editCell = editCells[key];
                if (editCell.id) {
                    updateCells.push(editCell);
                } else if (editCell.rowId) {  //已存在列里面添加
                    existsRowAddCells.push(editCell);
                } else {
                    _rowId = key.split('_')[0];
                    if (cache[_rowId]) {
                        if (!cache[_rowId].cells) {
                            cache[_rowId].cells = [];
                        }
                        cache[_rowId].cells.push(editCell);
                    }
                }
            }

            $http({
                method: 'POST',
                url: '/grule-manager/decision-tables/saveDecision',
                data: {
                    tableId: tableId,
                    delRowIds: delRowIds,
                    addRows: addRows,
                    updateRows: updateRows,
                    updateCells: updateCells,
                    existsRowAddCells: existsRowAddCells
                }
            }).success(function(resp){
                if (resp.success) {
                    initDecisions();
                    if(!fn){

                    }else {
                        GillionMsg.alert('提示', '保存成功', function () {
                            if (angular.isFunction(fn)) {
                                fn();
                            }
                        });
                    }
                }
            });
        };
    };
});